package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/charmbracelet/bubbles/textinput"
	tea "github.com/charmbracelet/bubbletea"
)

type model struct {
	MsgHistory []string
	ResHistory []string
	CmdInput   textinput.Model
	idx        int
}

func initialModel() model {
	ti := textinput.New()
	ti.Width = 20
	ti.Focus()

	return model{
		MsgHistory: []string{},
		ResHistory: []string{},
		CmdInput:   ti,
		idx:        0,
	}
}

func (m model) Init() tea.Cmd {
	return textinput.Blink
}

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmd tea.Cmd
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.Type {
		case tea.KeyCtrlC, tea.KeyEsc:
			return m, tea.Quit
		case tea.KeyEnter:
			ti := textinput.New()
			ti.Width = 20
			ti.Focus()
			m.MsgHistory = append(m.MsgHistory, m.CmdInput.Value())
			m.idx = len(m.MsgHistory)
			m.ResHistory = append(m.ResHistory, "ok")
			m.CmdInput = ti
		case tea.KeyUp:
			m.idx -= 1
			if m.idx <= 0 {
				m.idx = 0
			}
			m.CmdInput.SetValue(m.MsgHistory[m.idx])
		case tea.KeyDown:
			m.idx += 1
			if m.idx >= len(m.MsgHistory) {
				m.idx = len(m.MsgHistory) - 1
			}
			m.CmdInput.SetValue(m.MsgHistory[m.idx])
			m.CmdInput.SetCursor(1000)
		}
	}

	m.CmdInput, cmd = m.CmdInput.Update(msg)
	return m, cmd
}

func (m model) View() string {
	var b strings.Builder
	size := len(m.MsgHistory)
	for i := 0; i < size; i++ {
		b.WriteString("> " + m.MsgHistory[i] + "\n")
		b.WriteString(m.ResHistory[i] + "\n")
	}
	b.WriteString(m.CmdInput.View())
	return fmt.Sprintf("%s \n", b.String())
}

func main() {
	p := tea.NewProgram(initialModel())
	if _, err := p.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "启动程序时出错: %v\n", err)
	}
}
